<?php
/**
*   +----------------------------------------------------------------------
*   | Author: ONLY <491518132@qq.com>
*	+----------------------------------------------------------------------
*   | Creater Time : 2013-5-7
*   +----------------------------------------------------------------------
*   | Link (http://www.cloudsskill.com http://www.goshopx.com  http://www.shopingj.com )
*   +----------------------------------------------------------------------
**/

/**
 * 获取产品及其相关信息类
 *
 * 查询信息默认的都是根据产品ID做索引
 */
class  Product {
	protected $proattr,$product,$procate,$catetag,$attrcate,$brand,$description,$catetemp,$package,$catechildren,$attrgroups;
	public function __construct(){
		$this->product = M( 'Product' );
		$this->attribute = M('Attribute');
		$this->attrcate = M('CategoryAttribute');
		$this->proattr = M('ProductAttribute');
		$this->brand = M('ProductBrand');
		$this->procate = M('ProductCategoryTag');
		$this->catetag = M('ProductToCategoryTag');
		$this->description = M('ProductDescription');
		$this->priceb2b = M("ProductPriceB2b");
		$this->package = M('product_package');
		$this->catechildren = array();
		$this->catetemp = array();
		$this->attrgroups = array();
		
	}

	/**
	 * 筛选
	 * @param array $_condition
	 * @param array $_select
	 * @return array $rearray 返回条件，产品IDS
	 */
	function condition ($_condition,$_select = false) {
		is_array($_condition) ? true : $this->_message('', __LINE__, '请传数组参数！');
		$proids = array();
		$old = unserialize(mydecode($_condition['old']));
		
		$condition = array();
		$condition['keyword'] = $_condition['keyword'] ? $_condition['keyword'] : $old['keyword'];
		if($_condition['delkeyword'] || ! $condition['delkeyword']){
			unset($condition['delkeyword']);
		}
		
		$condition['brand'] = $_condition['brand'] ? $_condition['brand'] : $old['brand'];
		
		if($_condition['delbrand'] || ! $condition['brand']){
			unset($condition['brand']);
		}
		$condition['cate'] = $_condition['cate'] ? $_condition['cate'] : $old['cate'];
		if($condition['cate'] == '' || empty($condition['cate'])){		
			$condition['cate'] = 0;
		}
		$condition['tags'] = $_condition['tags'] ? $_condition['tags'] : $old['tags'];
		if(! $condition['tags']){
			unset($condition['tags']);
		}
		if($_condition['delattr']){
			$temp = explode(',',$old['attr']);
			$key = array_search($_condition['delattr'],$temp);
			unset($temp[$key]);
			$condition['attr'] = implode(',',$temp);
		}elseif($_condition['attr']){
			if($old['attr']){
				$oldids = explode(',',$old['attr']);
				$attrid = is_array($_condition['attr']) ? $_condition['attr'] : array($_condition['attr']);
				//查出传过来的属性属于那个属性
				$attrarray = $this->catetoattr($condition['cate']);
				$attrs = array();
				foreach ($attrarray as $k => $v){
					$temp = array_keys($v['value']);
					if(array_intersect($attrid, $temp)){
						$attrs = $temp;
					}
				}
				//选出新属性
				$tempid = array_intersect($oldids, $attrs);
				if($tempid){
					if(is_array($tempid)){
						foreach ($tempid as $k => $v){
							$key = array_search($v, $oldids);
							unset($oldids[$key]);
						}
						array_push($oldids, array_shift($attrid));
					}else{
						$key = array_search($v, $oldids);
						unset($oldids[$key]);
						array_push($oldids, array_shift($attrid));
					}
					$condition['attr'] = implode(',',$oldids);
				}else{
					$pieces = array_merge($oldids,$attrid);
					$condition['attr'] = implode(',', $pieces);					
				}
			}else{
				$condition['attr'] = $_condition['attr'];
			}
		}else{
			$old['attr'] ? $condition['attr'] = $old['attr'] : false;
		}
		$attributeids = array(); 
		if($condition['attr']){
			$attributeids = explode(',',$condition['attr']);
		}
		$proids = $this->proids($condition['cate'], $condition['tags'],$attributeids, $condition['brand'],$condition['keyword'] );
		$condinfo = array();
		if($condition['brand']){
			$condinfo['brand'] = $this->brand->field('id,name,alias')->where(array('id'=>$condition['brand']))->find();
		}
		if($condition['attr']){
			$atid = strpos($condition['attr'], ',') ? explode(',',$condition['attr']) : $condition['attr'];
			$condinfo['attr'] = $this->attr($atid);
		}
		$rearray = array();
		$rearray['condinfo'] = $condinfo;
		$old=array();
		foreach ($condition as $k=>$v){
			if($v){
				$old[$k]=$v;
			}
		}
		$rearray['old'] = myencode(serialize($old));
		$rearray['proids'] = $proids;
		return $rearray;
	}
	
	/**
	 * 产品筛选信息
	 * @param int | array $_cateid
	 * @param int | array $_tagids
	 * @param int | array $_attrids
	 * @param int | array $_brid
	 * @return array $proids 返回产品ids
	 */
	function proids ($_cateid,$_tagids,$_attrids,$_brid,$_keyword = false) {
		if($_cateid == '3' || $_cateid == '70'){
			$_attrids[] = '170';
		}
		$proids = array();
		$proids['cid'] = $this->catetoproduct($_cateid); 
		if(empty($proids['cid'])){return $proids;}
		$_tagids ? $proids['tid'] = $this->tagtopro($_tagids) : false;
		$proids['tid'] ? $proids['tid'] = $this->arr2to1($proids['tid'],'product_id') : false;
		$_attrids ? $proids['aid'] = $this->attrtopro($_attrids) : false;
		$_brid ? $proids['bid'] = $this->bratopro($_brid) : false;
		$_keyword ? $proids['keyid'] = $this->search($_keyword) : false;
		$proids = $this->intersection($proids);
		return $proids;
	}
	
	/**
	 * 产品搜索
	 * @param string $_proname
	 * @return array $proids
	 */
	function search ($_keyword) {
		$model = M();
		$sql = "SELECT p.id FROM product as p LEFT JOIN product_description as d ON d.product_id=p.id WHERE p.status=1 AND d.`name` LIKE '%$_keyword%'";
		$proids = $model->query($sql);
// 		echo $model->getLastSql();
		$proids = $this->arr2to1($proids,'id');
		return $proids;
	}

	/**
	 * 根据“已排序的产品ID”返回产品列表 (排序)
	 * @param int | array $_proids 已排序的产品列表
	 * @param string $_offset
	 * @param array $_sequense
	 */
	function prolist($_proids,$_offset,$_order){		
		$map['id'] = is_array($_proids) ? array('IN',implode(',', $_proids)) : $_proids;		
		$_offset = $_offset ? $_offset : '';			
		//$order = $_order ? $_order : 'write_date DESC';
		//产品		
		$prolist = $this->product->field('id,name,ROUND(price/100) as price,image,status,code,brand_id')->limit($_offset)->order($_order)->where($map)->select();
		$list = field2key($prolist,'id');
		 return $list;			
	}
		
	
	/**
	 * 根据产品ID返回产品列表
	 * @param int | array $_proids
	 * @param string $_offset
	 * @param string $_sequense
	 */
	function prolistinfo($_proids,$_offset,$_sequense){
		$where['id'] = is_array($_proids) ? array('IN',implode(',', $_proids)) : $_proids;
		$order = $_sequense ? $_sequense : 'write_date DESC';
		$_offset = $_offset ? $_offset : '';
		$prolistinfo = $this->product->field('id,image,name,price,mian_cat cateid')->where($where)->order($order)->limit($_offset)->select();
		
// 		$cateid = $this->_procate(array_shift($_proids));
// 		$ids=arr_to_explode($prolistinfo,'id','');
// 		foreach ($prolistinfo as $k => &$v){
// 			$v['name'] = $temp[$v['id']]['name'];
// 			$v['alias'] = $temp[$v['id']]['alias'];
// 			$v['cateid'] = $cateid[0]['category_tag_id'];
// 			$v['price'] = $this->_price_b2b($v['id']);
// 		}
		return $prolistinfo;
	}
	
	/**
	 * 根据产品ID返回产品列表
	 * @param int | array $_proids
	 * @param string $_offset
	 * @param string $_sequense
	 */
	function prolistinfo1($_proids,$_offset,$_sequense){
		//$where['id'] = is_array($_proids) ? array('IN',implode(',', $_proids)) : $_proids;
		$where['product.id'] = is_array($_proids) ? array('IN',implode(',', $_proids)) : $_proids;
		$where['check_product.status'] = 1;
		$order = $_sequense ? $_sequense : 'write_date DESC';
		$_offset = $_offset ? $_offset : '';
		//$prolistinfo = $this->product->field('id,image')->where($where)->order($order)->limit($_offset)->select();
		
		$prolistinfo = $this->product->join('LEFT JOIN check_product ON product.id=check_product.product_id ')->field('product.id,product.image,check_product.point')->where($where)->order($order)->limit($_offset)->select();
		
		//dump( $this->product->getLastSql());
		
		$cateid = $this->_procate(array_shift($_proids));
		$ids=arr_to_explode($prolistinfo,'id','');
		$temp = $this->description($ids,'product_id,name,alias');
		foreach ($prolistinfo as $k => &$v){
			$v['name'] = $temp[$v['id']]['name'];
			$v['alias'] = $temp[$v['id']]['alias'];
			$v['cateid'] = $cateid[0]['category_tag_id'];
			$v['price'] = $this->_price_b2b($v['id']);
		}
		return $prolistinfo;
	}
	
	/**
	 * 返回产品分类
	 * @param int | array | string $_ids
	 * @return array $cateid
	 */
	function _procate($_ids){
		$model = M('ProductToCategoryTag');
		$where['product_id'] = is_array($_ids) ? count($_ids) > 1 ? array('IN',implode(',', $_ids)) : array_shift($_ids) : $_ids;
		$cateid = $model->field('category_tag_id')->where($where)->select();
// 		echo $model->getLastSql();
		return $cateid;
	}
	
	/**
	 * 排序后返回产品id （针对产品列表）
	 * @param string $model（需要排序的表:Product）
	 * @param string $key (产品id 所在表的字段：如Product表就是“id” ，Product_description 就是“product_id”)
	 * @param array $map 查询条件
	 * @param string $order(排序字段: name asc)
	 * @param string $limit (分页查找的数量)
	 * @return array $pro_ids 排序后的产 id 数组
	 */
	function orderlist($model,$key,$map,$order,$limit){
		$m = M($model);
		$res = $m->field($key)->where($map)->order($order)->limit($limit)->select();
		if($_REQUEST['mw']){
			echo $m->getLastSql();
			dump($res);
		}
		$pro_ids = array();
		foreach ($res as $vo){
			$pro_ids[] = $vo[$key];
		}
		return $pro_ids;
	}
	
	

	/**
	 * 根据产品ID返回靓号运营商
	 * @param int | array $_proids 产品id
	 * @return array(array('product_id','value'))
	 */
	function lh_service($_proids){
		$map['product_id'] = is_array($_proids) ? array('IN',implode(',', $_proids)) : $_proids;
		$res = $this->proattr
		->join(' as proattr left join attribute as attr ON proattr.attribute_id = attr.id' )
		->field('product_id,value')
		->where($map)->select();
		return $res;
	}
	
	
	/**
	 * 根据分类返回产品ID
	 * @param int $_cid 分类ID
	 * @return array $prodcut_ids
	 */
	function catetoproduct($_cid){
		$_cid = intval($_cid);
		$cid_arr = $this->catelist($_cid);
		$temp = NULL;
		if(($_cid == 0) || ($_cid == '')){
			$temp = array_shift($cid_arr);
			$temp = $temp['chiled'];
		}else{
			$temp = $cid_arr;
		}
		$sb = FALSE;
		foreach ($temp as $k => $v){
			if(is_array($v)){
				$sb = TRUE;
				break;
			}
		}
		$ids = $sb ? $this->arr2to1($temp,'id') : $temp['id'];
		$model = M();
		if($sb){
			$cids = implode(',', $ids);
			$sql = "SELECT p.id FROM product as p LEFT JOIN product_to_category_tag as c ON p.id=c.product_id WHERE c.category_tag_id IN ($cids) AND p.`status`=1";
		}else{
			$sql = "SELECT p.id FROM product as p LEFT JOIN product_to_category_tag as c ON p.id=c.product_id WHERE c.category_tag_id=$ids AND p.`status`=1";
		}
		$ids = $model->query($sql);
// 		echo $model->getLastSql();
		$proids = $this->arr2to1($ids, 'id');
		return $proids;
	}
	
	/**
	 * 返回分类详细信息
	 * @param array|int $_ids
	 * @return array $info
	 */
	function catetoinfo($_ids){
		$model = M('ProductCategoryTag');
		$where['id'] = is_array($_ids) ? array('IN',implode(',', $_ids)) : array('IN',"$_ids");
		$info = $model->field('id,name')->where($where)->select();
		return $info;
	}
	
	/**
	 * 分类
	 * @param int $pid 空为所有分类
	 * @param boolean $_debug 返回SQL语句
	 * @return array $cate
	 */
	function catelist($_id,$_retype = TRUE,$_debug = false){
		//重新定义 catetemp 参数。
		$this->catetemp = array();
		$where['type'] = '1';
		$cate = $this->procate->where($where)->select();
		if($_debug){
			return dump($this->procate->getLastSql());
			exit;
		}
		$category = $_id ? $this->_catlist($cate, $_id) : $this->_category($cate);
		if($_retype){
			if(! $category){
				$category = $this->procate->where(array('id'=>$_id))->find();
			}
		}
		return $category;
	}
	
	/**
	 * 返回树形菜单
	 * @param array $_cate
	 * @return array $_cate
	 */
	function catelevel ($_cate,$_level = 3) {
		foreach ($_cate as $k => &$v){
			$stra = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|';
			$strb = '&nbsp;--&nbsp;';
			$strc = '';
			if($v['level'] < $_level){
				for($i=0;$i<$v['level'];$i++){
					$strc = $strc.$stra;
				}
				$v['name'] = $strc.$strb.$v['name'];
			}else{
				unset($_cate[$k]);
			}
		}
		return $_cate;
	}
	
	/**
	 * 获取所有的上级分类
	 * @param int $pid 空为所有分类
	 * @param boolean $_debug 返回SQL语句
	 * @return array $cate
	 */
	function parent_catelist($_id,$_debug = false){
		$where['type'] = '1';
		$where['id'] = $_id;
		$cate = $this->procate->where($where)->find();
		if($_debug){
			return dump($this->procate->getLastSql());
			exit;
		}
		$category = $this->_parentcatlist($cate, $_id);
		return $category;
	}
	
	
	/**
	 * 处理产品分类
	 * @param array $_categorys 产品分类
	 * @return array
	 */
	protected function _category ($_categorys) {
		$temp = array();
		foreach ($_categorys as $k=>$v){
			$this->catetemp = array();
			if($v['parent_id'] == '0'){
				$temp[$k] = $v;
				$temp[$k]['chiled'] = $this->_catlist($_categorys,$v['id']);
			}
		}
		return $temp;
	}
	
	/**
	 * 返回分类父级层次
	 * @param array $_categorys 产品分类数组集
	 * @param string $_id 此ID下的分类
	 * @param string $_level 结构层次
	 * @return array
	 */
	protected function _parentcatlist ($_categorys,$_id,$_level=0){
		if(empty($_categorys['path'])) return;
		$where['type'] = '1';
		$where['id'] = array('in',$_categorys['path']);
		$parent_catelist = $this->procate->where($where)->select();
		$parent_catelist[] = $_categorys;
		return $parent_catelist;

// 		$parent_catelist = array();
// 		foreach ($_categorys as $k => $v){
// 			if($v['id'] == $_id ){print_r($v);}
// 			if(156 == $v['id'] && $v['path']!=0){echo 234;
// 				$this->parentcatetemp[$v['id']] = $v;
// 				$this->parentcatetemp[$v['id']]['level'] = $_level;
// 				$this->_parentcatlist($_categorys,$v['parent_id'],$_level+1);
// 				break;
	
// 			}
// 		}
// 		return $this->parentcatetemp;	
	}
	
	
	/**
	 * 返回分类层次
	 * @param array $_categorys 产品分类数组集
	 * @param string $_id 此ID下的分类
	 * @param string $_level 结构层次
	 * @return array
	 */
	protected function _catlist ($_categorys,$_id,$_level=0){	
		foreach ($_categorys as $k => $v){
			if($_id == $v['parent_id']){
				$this->catetemp[$v['id']] = $v;
				$this->catetemp[$v['id']]['level'] = $_level;
				$this->_catlist($_categorys,$v['id'],$_level+1);
			}
		}
		return $this->catetemp;
	}
	
	
	
	/**
	 * 返回属性值
	 * @param array or int $_ids 属性ID返回值
	 * @param boolean $_debug 返回SQL语句
	 * @return array $attr
	 */
	function attr($_ids = false,$_debug = false){
			$where['id'] = is_array($_ids) ? array('in',implode(',',$_ids)) : $_ids;
			$attr = $this->attribute->where($where)->select();
			if($_debug){
				return dump($this->attribute->getLastSql());
				exit;
			}
			return $attr;
	}
	
	
	/**
	 * 返回分类下属性组 
	 * @param int $_cateid 返回分类下属性组 
	 * @param boolean $_debug 返回SQL语句
	 * @return array $attrgroup
	 */
	function catetoattr($_cateid = false,$_debug = false) {
		$code = $this->attrcate->field('code')->where(array('category_id'=>$_cateid))->find();
		$attrvalue = $this->attribute->where(array('code'=>$code['code'],'status'=>'1'))->select();
		$temp = $this->attribute->where(array('code'=>$code['code'],'status'=>'1'))->group('name')->order('sequence DESC')->select();
		if($_debug){
			dump($code);
			return dump($this->attrcate->getLastSql());
			exit;
		}
		$attrgroup = array();
		foreach ($temp as $key => $val){
			$attrgroup[$key]['name'] = $val['name'];
			$attrgroup[$key]['alias'] = $val['alias'];
			foreach ($attrvalue as $k => $v){
				if($val['name'] == $v['name']){
					$reid = $this->attrtopro($v['id']);
					if($reid){
						$attrgroup[$key]['value'][$v['id']] = $v['value'];
					}
					unset($attr[$k]);
				}
			}
		}
		return $attrgroup;
	}
	
	/**
	 *获取关联的属性组及属性值
	 *@date 2013-9-26
	 *@time 下午3:59:03
	 *@update by tb 2013.12.30
	 */
	function cattoattribute($cid=0,$platform_parm='',$status=1) {
		//获取关联的属性组
		$platform = 'ALL';
		$catdao=M('CategoryAttribute');
		$where=array();
		$where['category_id']=$cid;
		if($platform_parm){
			$platform_parm=strtoupper($platform);
			$platform .=' ,'.$platform_parm;
			$where['platform'] = array('IN',$platform);
		}else{
			$where['platform'] = $platform;
		}
		$where['name'] =  array('NEQ' , '');
		
		
// 		if($platform!='ALL'){
// 			$platformstr=array();
// 			if(strpos($platform,',')!==false){
// 				$platforms=explode(',', $platform);
// 				foreach ($platforms as $v){
// 					$platformstr[]=' FIND_IN_SET('.$v.',`platform`)>0 ';
// 				}
// 				$platformstr=implode('OR', $platformstr);
// 			}else{
// 				$platformstr=' FIND_IN_SET('.$v.',`platform`)>0 ';
// 			}
// 			$where['_String']=$platformstr;
// 		}

		$attr = $catdao->join(' as ca left join attribute as a on ca.attr_id = a.id')->field('')->where($where)->order('sequence DESC')->select();
// 		print_r($res);
// 		$res=$catdao->where($where)->order('sequence DESC')->select();
// 		if(empty($res)){
// 			return 0;
// 		}
// 		$aids=arr_to_explode($res,'attr_id',',');
// 		$attrdao=M('Attribute');
// 		$where=array();
// 		if($status!==false){
// 			$where['status']=$status;
// 		}
// 		$where['id']=array('IN',$aids);
// 		$attr=$attrdao->where($where)->select();
// 		if(empty($attr)){
// 			return 0;
// 		}
		return $attr;
	}//end cat_attr
	
	/**
	 * 返回标签关联产品ID
	 * @param int | array $_tagids 标签ID
	 * @param string $_debug
	 * @return array $tagpro
	 */
	function tagtopro($_tagids,$_debug = false){
		$tagpro = array();
		$where['type'] = '3';
		if(is_array($_tagids)){
			$_tagids = implode(',',$_tagids);
			$where['category_tag_id'] = array('IN',$_tagids);
		}else{
			$where['category_tag_id'] = $_tagids;
		}
		$tagpro = $this->catetag->field("product_id,count('product_id') as pid")->where($where)->group('product_id')->select();
		if($_debug){
			dump($this->catetag->getLastSql());
			exit;
		}
		return $tagpro;
	}
	
	
	/**
	 * 根据属性ID返回产品ID
	 * @param int or array $_aid 属性ID 可以是一维数组
	 * @param string $_debug 调试
	 * @return array $proids 返回产品
 	 */
	function attrtopro($_aid,$pids=true,$_debug = false) {
		$where= array();
		if(is_array($_aid)){
			$ids = array();
			foreach ($_aid as $k => $v){
				$where['attribute_id'] = $v;
				$temp = $this->proattr->field('product_id')->where($where)->group('product_id')->select();
				foreach ($temp as $v){
					$ids[$k][] = $v['product_id'];
				}
			}
			$proids = $this->intersection($ids);
			return $proids;
		}else{
			$where['attribute_id'] = $_aid;
			$ids = $this->proattr->field('product_id')->where($where)->group('product_id')->select();
			if($_debug){
				return dump($this->proattr()->getLastSql());
				exit;
			}
			$proid = array();
			foreach ($ids as $v){
				$proid[] = $v['product_id'];
			}
			return $proid;
		}
	}
	
	function protocate ($_ids) {
		$where['product_id'] = is_array($_ids) ? array('IN',implode(',', $_ids)) : $_ids;
		$where['category_tag_id'] = array('NEQ','138');
		$ids = $this->catetag->field('category_tag_id as cateid,group_concat(product_id) as proid')->cache(true,300)->where($where)->group('category_tag_id')->select();
		$info = array();
		foreach ($ids as $k => $v){
			$path = $this->procate->field('path')->where(array('id'=>$v['cateid']))->find();
			$pid = explode(',', $path['path']);
			$v['pid'] = $pid['2'] ? $pid['2'] : $v['cateid'];
			$name = $this->procate->field('name')->where(array('id'=>$v['pid']))->find();
			$v['name'] = $name['name'];
			$info[$k] = $v;
		}
		$temp = array();
		foreach ($info as $k => $v){
			foreach ($info as $key => $val){
				if($v['pid'] == $val['pid'] && $v['cateid'] != $val['cateid']){
					$v['proid'] = array_merge(explode(',',$v['proid']),explode(',', $val['proid']));
					$temp[$v['pid']] = $v;
					unset($info[$key]);
				}
			}
			$temp[$v['pid']] = $v;
			$temp[$v['pid']]['proid'] = explode(',', $temp[$v['pid']]['proid']);
		}
		return $temp;
	}
	
	
	/**
	 * 二维数组返回一维或字符串
	 * @param array $_arr
	 * @param string $_field
	 * @param string $_type 1为数组 2为字符串
	 * @return multitype:array|multitype:string
	 */
	function arr2to1($_arr,$_field = '0',$_type = '1'){
		if ( ! $_arr ) return array();
		$arrayids = array(); 
		foreach ($_arr as $k => $v){
			$arrayids[$k] = $v[$_field];
		}
		if($_type != '1') $arrayids = implode(',',$arrayids);
		
		return $arrayids;
	}
	
	/**
	 * 返回二维数组里面元素的交集
	 * @param array $_arr 二维数组
	 * @return $value 返回二维数组里面元素的交集
	 */
	function intersection($_arr) {
		$value = array();
		$init = true;
		if(count($_arr) == '1'){
			return array_shift($_arr);
		}else{
			foreach ($_arr as $k => $v){
				if(empty($value) && $init){
					$value = $v;
				}else{
					$value = array_intersect($value,$v);
					$init = false;
				}
			}
			return $value;
		}
	}
	
	/**
	 * 产品属性
	 * @param int $_proid 
	 * @param array $_field 字段
	 * @param boolean $_debug 返回SQL语句
	 * @return array $proattr
	 */
	function protoattr($_proid,$_field = '*',$_debug = false){
		$where['product_id'] = $_proid;
		$temp = $this->proattr->field($_field)->where($where)->select();
		if($_debug){
			return dump($this->proattr()->getLastSql());
			exit;
		}
		$id = array();
		foreach ($temp as $v){
			$id[] = ','. $v['attribute_id'];
		}
		$proattr = $this->attr($id);
		return $proattr;
	}
	
	/**
	 * 产品分类信息
	 * @param int $_proid
	 * @param array $_field 字段
	 * @return array $list
	 */
	function procat($_proid,$_field = '*'){
		$where['product_id'] = is_array($_proid) ? array('IN',implode(',', $_proid)) : $_proid;
		$res = $this->catetag->field($_field)->cache(true,300)->where($where)->select();
		$list = array();
		foreach ($res as $vo){
			$list[] = $this->procate->field('name')->find($vo['category_tag_id']);
		}
		return $list;
	}
	
	
	/**
	 * 根据分类ID返回品牌列表
	 * @param int $_cate 分类
	 * @param boolean $_debug 返回SQL语句
	 * @return array $brand || $product
	 */
	function brand ($_cate = false,$_debug = false){
		$where['status'] = '1';
		if(!empty($_cate)){
			$_field = 'id,name,alias';
			$pids = $this->catetoproduct($_cate);
			$pids = implode(',', $pids);
			$where['id'] = array('IN',$pids);
			$brand = $this->product->field('brand_id')->where($where)->group('brand_id')->select();
// 			echo $this->product->getLastSql();
			$brand = $this->arr2to1($brand,'brand_id',2);
			$where['id'] = array('IN',$brand);
			$brand = $this->brand->field($_field)->where($where)->select();
			if($_debug){
				return dump($this->brand->getLastSql());
				exit;
			}
			return $brand;
		}else{
			return false;
		}
	}
	
	/**
	 * 返回品牌信息
	 * @param int|array $_ids
	 * @return array $info
	 */
	function brandinfo($_ids){
		$model = M('ProductBrand');
		$where['id'] = is_array($_ids) ? array('IN',implode(',',$_ids)) : array('IN',"$_ids");
		$info = $model->field('id,name')->where($where)->select();
// 		echo $model->getLastSql();
		return $info;
	}
	
	/**
	 * 根据品牌ID返回产品ID
	 * @param 品牌ID $_bid
	 * @return array $proids
	 */
	function bratopro($_bid = false,$_debug = false){
		$where['status'] = '1';
		if($_bid){
			$where['brand_id'] = $_bid;
			$where['status'] = 1;
			$product = $this->product->field('id')->where($where)->select();
			if($_debug){
				return dump($this->product->getLastSql());
				exit;
			}
			$proids = $this->arr2to1($product,'id');
			return $proids;
		}else{
			return false;
		}
	}
	
	/**
	 * 产品基本信息
	 * @param int or array $_proid
	 * @param array $_field 字段
	 * @return array $des
	 */
	function product($_proid,$_field = '*',$status='all'){
		$map['id'] = $_proid;
		if($status!='all'){
			$map['status'] = $status;
		} 
		$des = $this->product->field($_field)->where($map)->find();
		return $des;
	}
	
	/**
	 * 产品描述
	 * @param int or array $_proid
	 * @param array $_field 字段
	 * @return array $des
	 */
	function description($_proid,$_field = '*'){
		if ( is_array($_proid)){
			$id = implode(',',$_proid);
			$map['product_id'] = array('in',$id);
			$des = $this->description->field($_field)->where($map)->select();
			$des=field2key($des,'product_id');
			return $des;
		} else{
			$des = $this->description->field($_field)->where(array('product_id'=>$_proid))->select();
			return $des;
		}
	}
	
	
	/**
	 * 随机推荐产品
	 * @param string $_limit
	 * @return $proids
	 */
	function randpro ($_limit,$levle=0) {
		$where['id'] = array('ELT',10000);
		$where['status'] = 1;
		$reids = $this->product->field('id')->where($where)->order('rand()')->limit($_limit)->select();
		
		if($reids){
			foreach ($reids as $vo){
				$proids[] = $vo['id'];
			}			
			$prolist = $this->prolist($proids);

		}
		return $prolist;
	}
	
	/**
	 * 关联产品查询
	 * @param 产品ID $_id
	 * @return array $info
	 */
	function relevance($_id,$_status = false){
		$model = M();
		$st = $_status ? ' AND p.status = 1' : false;
		$sql = "SELECT r.id rid,p.id pid,p.`name`,p.mian_cat,p.`status`,p.price,p.image FROM `product_related` r LEFT JOIN product p ON r.`to`=p.id WHERE r.`from`=".$_id.$st;
		$info = $model->query($sql);
// 		echo $model->getLastSql();
		return $info;
	}
	
	/**
	 * 返回b2b用户浏览记录
	 * @param int $_uid 用户ID
	 * @return array $Info
	 */
	function b2bseelog($_uid){
		$model = M('Clicks');
		$sql = "SELECT p.id,p.`name`,p.price,p.image FROM `clicks` c LEFT JOIN product p ON c.productid=p.id WHERE c.user_id=".$_uid." AND p.`status`=1  AND c.plantform='b2b' GROUP BY c.productid LIMIT 0,5";
		$info = $model->query($sql);
// 		echo $model->getLastSql();
		return $info;
	}
	
	/**
	 * 返回提示信息
	 * @param multitype $_val
	 * @param json
	 */
	function _message($_val,$_line,$_msg){
		if(!$_val || empty($_val) || $_val === 'false'){
			$mesg=array("status"=>0,'msg'=>$_msg.'在'.$_line.'行');
			exit(json_encode($mesg));
		}else{
			$mesg=array("status"=>1,'msg'=>$_msg);
			exit(json_encode($mesg));
		}
	}

	
	
	
	/**
	 * 获取产品图片
	 * @param mixed $id 产品ID
	 * @return array
	 */
	function get_img($id){
		$dao = M("product_image");
		$map = array();
		if ( ! is_array($id) ) $map['id'] = $id;
		else $map['id'] = array('in', implode(',',$id));
		$img_list = $dao->where( $map )->select();
		return $img_list;
	}
	
	/**
	 * 获取产品基本信息列表
	 * @param int|array $ids
	 */
	function get_baseinfo_list($ids){
		$products = $this->product($ids);
		if ( ! $products ) {
			echo 'no msg';
		}else{
			$prices       = $this->get_price($ids);
			$descriptions = $this->description($ids);
			foreach ( $products as $key=>$value ) {
				$temp = $this->array_into_merge($prices, $value, 'o2o_price', 'product_id');
				$value = $this->array_into_merge($descriptions, $temp, 'name', 'product_id');
				$products[$key] = $value;
			}
		}
		return $products;
	}
	
	/**
	 * 获得关联产品
	 * @param string|int $id
	 * @return array
	 */
	function get_related($id){
		$dao = M('product_related');
		$map['id'] = $id;
		$related = $dao->where($map)->select();
		return $related;
	}
	
	function get_by_attrs($ids){
		if ( is_array($ids) ) $ids = implode(',', $ids);
		$count = substr_count($ids, ',') + 1;
		$dao = M('product_attribute');
		$map['attribute_id'] = array('in', (string) $ids);
		$products = $dao->field("product_id,count(product_id) as num_p")->where( $map )->group('product_id')->having("num_p=".$count)->select();
		return $products;
	}
	
	/**
	 * 合并数据，一个数组充当另一个数组的一个元素
	 * @param array $arr
	 * @param array $box
	 * @param string $index
	 * @param string $key
	 * @param string $id
	 */
	function array_into_merge($arr, $box, $index, $key, $id='id') {
		if ( ! $arr ) return;
		foreach ( $arr as $val ) {
			if ( $box[$id] == $val[$key] ) $box[$index] = $val;
		}
		return $box;
	}
	
	
	/**
	 * 检索 产品描述表 返回 字段name 包含 传人参数 的产品信息 数组
	 */
	function get_mate_list($_value = ''){
		if($_value == '') return;
		$map['name'] = array('like', '%'.$_value.'%');
		$des  = $this ->description -> where( $map) -> field ('name') ->select ();
		return $des;
	}
	
	/**
	 * 获取套餐产品
	 * 检索 product_package 返回 id在$_id其中的 且当前时间在规定范围内的 价格
	 * 返回数组
	 */
	function get_package ($_id) {
		if( ! $_id ) return false;
		
		$map['start_time'] =  array( array('ELT', time()) ,array('EQ','-1'),'or');
		$map['end_time']   =  array( array('EGT', time()), array('EQ','-1'),'or');
		$map['_string'] = " find_in_set({$_id}, product_ids) ";
		$des  = $this ->package -> where( $map) -> field ('special_price') -> select ();
		return $des;
	}

	/**
	 * 返回此产品详细信息
	 * @param string $_proid
	 * @return array $oneproinfo
	 */
	function oneproinfo($_proid){
		
		$name = $this->_description($_proid);
		$image = $this->_mainimage($_proid);
	
		$oneproinfo = array();
		$oneproinfo['base'] = $this->product($_proid,'id,brand_id,mian_cat,name,image,code,status');
		$oneproinfo['des'] = $name;
		$oneproinfo['image'] = $image;
		$oneproinfo['code'] = $this->_procode($_proid);
		$oneproinfo['groupimage'] = $this->_image($_proid);
		$oneproinfo['imagecount'] = count($oneproinfo['groupimage']);
		$oneproinfo['price'] = $this->_price_b2b($_proid);
	
		return $oneproinfo;
	}
	
	/**
	 * b2b需要的价格
	 * 列出所有的价格
	 */
	function _price_b2b($proid,$unit=true){
		$price_m = M('ProductPriceB2b');
		$proid = intval($proid);
		if ( ! $proid ) return false;
		$field = 'minsale,ROUND(price/100) as price,ROUND(jiayi/100) as jiayi,ROUND(jiaer/100) as jiaer,ROUND(jiasan/100) as jiasan,ROUND(jiasi/100) as jiasi ,ROUND(jiawu/100) as jiawu ,ROUND(jialiu/100) as jialiu';
		if ( ! $field ) $field = 'price,jiayi,jiaer,jiasan,jiasi,jiawu,jialiu';
		$prict_list = $price_m->field( $field )->where( array('product_id'=>$proid) )->find();
		return $prict_list;
	}
	
	
	/**
	 * 产品描述
	 * @param int or array $_proid
	 * @return array $des
	 */
	function _description($_pid){
		$description = $this->description->field('id,init_id,key_id',true)->where(array('product_id'=>$_pid))->find();
		return $description;
	}
	
	/**
	 * 返回产品主图
	 * @param string $_proid
	 * @return array $mainimage
	 */
	function _mainimage($_proid){
		$image = M('Product');
		$mainimage = $image->field('image')->where(array('id'=>$_proid))->find();
		$cateid = $this->category($_proid);
		$cateid = $cateid['category_tag_id'];
		if ( $cateid == 186 ) $mainimage['image'] = '/Public/v2/img/lhbg.jpg';
		return $mainimage['image'];
	}
	
	/**
	 * 获取产品图片
	 * @param mixed $id 产品ID
	 * @return array
	 */
	function _image($_id){
		$dao = M("product_image");
		$where['product_id'] = $_id;
		$gorugimage = $dao->field('url')->where($where)->select();
		return $gorugimage;
	}
	
	/**
	 * 返回产品的编码号
	 * @param string $_proid
	 * @return string $code
	 */
	function _procode($_proid){
		$code = $this->product->field('code')->where(array('id'=>$_proid))->find();
		return $code['code'];
	}
	
	/**
	 * 获取分类信息
	 * 暂做根据产品获取相应分类ID
	 * @param string $_proid 产品
	 * @return string $code
	 */
	function category($_proid){
		$category_id = $this->catetag->where(array('product_id'=>$_proid))->find();
		return $category_id;
	}
	
	
	//筛选 start
	
	//筛选过滤处理
	function filtrate($_condition){
		$proids = array();
		$old = unserialize(mydecode($_condition['old']));
		
		//del null
		foreach ($_condition as $k => $v){
			if(empty($v)){
				unset($_condition[$k]);
			}
		}
		
		$condition = array();
		//keyword
		$condition['keyword'] = $_condition['keyword'] ? $_condition['keyword'] : $old['keyword'];
		if($_condition['delkeyword']){
			unset($condition['keyword']);
		}
		
		//brand
		if($_condition['delbrand']){
			$key = array_search($_condition['delbrand'],$old['brand']);
			$condition['brand'] = $old['brand'];
			unset($condition['brand'][$key]);
 		}elseif($old['brand'] ||  $_condition['brand']){
			if($old['brand']){
				if(in_array($_condition['brand'],$old['brand'])){
					$condition['brand'] = $old['brand'];
				}else{
					$condition['brand'] = $old['brand'];
					$condition['brand'][] = $_condition['brand'];
				}
			}else{
				$condition['brand'][] = $_condition['brand'];
			}
		}

 		//category
		$condition['cate'] = $_condition['cate'] ? $_condition['cate'] : $old['cate'];
		if($condition['cate'] == '' || empty($condition['cate'])){		
			$condition['cate'] = 0;
		}
		
		//attribute
		$temp = array();
		$old['attr'] ? $temp['old'] = $old['attr'] : FALSE;
		$_condition['attr'] ? $temp['attr'] = $_condition['attr'] : FALSE;
		$_condition['delattr'] ? $temp['delattr'] = $_condition['delattr'] : FALSE;
		if(! empty($temp)){
			$condition['attr'] = $this->attrfiltr($temp);
			foreach ($condition as $k => $v){
				$i = true;
				if($v && is_array($v)){
					foreach ($v as $key => $val){
						if(empty($val)){
							unset($condition[$k][$key]);
						}else{
							$i = false;
						}
					}
				}elseif(empty($v) && $i){
					unset($condition[$k]);
				}
			}
		}
		
		//del null
		foreach ($condition as $k => $v){
			if(empty($v)){
				unset($condition[$k]);
			}
		}
		$condition['old'] = myencode(serialize($condition));
		return $condition;
	}
	
	
	/**
	 * 返回筛选条件后的产品ids
	 * @param array $_condition
	 * @return array $proids
	 */
	function filtrtoproids($_condition){
		$proids = array();
		$temp = array();
		//查找分类和子分类下面的产品
		if ( in_array($_condition['cate'], array(186,187))) {
			$map = array('mian_cat'=>$_condition['cate']);
			if ( $_condition['cate'] == 187 ) $map = array('mian_cat'=>$_condition['cate'],'mname'=>'hmpf');
			$ids_t = M('product')->field('id')->where( $map )->order('sequence desc,id desc')->select();
			$temp['cate'] = array();
			foreach ( $ids_t as $v_t ) {
				$temp['cate'][] = $v_t['id'];
			}
		} elseif($_condition['cate']){
			$res = $this->catetochildren($_condition['cate']);
			$_condition['cate'] = $this->arr2to1($res,'id');
			$temp['cate'] = $this->catetopro($_condition['cate']);
		}
		$_REQUEST['mw'] ? dump($_condition['cate']) : false;
		$_condition['brand'] ? $temp['brand'] = $this->brandtopro($_condition['brand']) : FALSE;
		$_condition['keyword'] ? $temp['keyword'] = $this->keyword($_condition['keyword']) : FALSE;
		$_condition['attr'] ? $temp['attr'] = $this->attrstopro($_condition['attr'],'',$_condition['cate']) : FALSE;
		$i = 0;
		foreach ($temp as $k => $v){
			if($i){
				$proids = array_intersect($proids, $v);
			}else{
				$proids = $v;
				$i++;
			}
		}
		return $proids;
	}
	
	
	/**
	 * 把筛选后的属性分组
	 * @param array $_attrs 筛选后的属性
	 * @return array $attrs;
	 */
	function attrfiltrs($_attrs,$catid = 3){
		$attrgroup = array();
		if($this->attrgroups){
			$attrgroup = $this->attrgroups;
		}else{
			$attrgroup = $this->cateattrgroup($catid);
		}
		$attrs = array();
		$temp = array();
		foreach ($attrgroup as $k => $v){
			$temp[$k] = $this->arr2to1($v,'id');
		}
		foreach ($_attrs as $k => $v){
			foreach ($temp as $key => $val){
				if(in_array($v,$val)){
					$attrs[$key][] = $v;
					break;
				}
			}
		}
		return $attrs;
	}
	
	/**
	 * 分类下的属性列表
	 * @param string $_catid
	 * @return array $attrgroup
	 */
	function cateattrgroup($_catid){
		$attrgroup =  array();
		$model = M('CategoryAttribute');
		$cateattr = $model->field('attr_id as aid')->where(array('category_id'=>$_catid))->select();
		$cateattr = $this->arr2to1($cateattr,'aid');
		$model = M('Attribute');
		$where = array();
		$where['id'] = array('IN',implode(',', $cateattr));
		$where['status'] = 1;
		$temp = $model->field('name,id,value')->where($where)->select();
		$i = 0;
		foreach ($temp as $k => $v){
			if($i){
				$attrgroup[$v['name']][] = $v;
			}else{
				if($attrgroup[$v['name']]){
					$attrgroup[$v['name']][] = $v;
				}else {
					$attrgroup[$v['name']][] = $v;
				}
			}
		}
		$this->attrgroups = $attrgroup;
		return $attrgroup;
	}
	
	/**
	 * 处理筛选属性
	 * @param array $_attrfiltr
	 * @return array $attr
	 */
	function attrfiltr($_attrfiltr){
		$attr = array();
		if($_attrfiltr['delattr']){
			$diff = array_search($_attrfiltr['delattr'], $_attrfiltr['old']);
			$attr = $_attrfiltr['old'];
			unset($attr[$diff]);
		}else {
			if($_attrfiltr['old']){
				if(in_array($_attrfiltr['attr'],$_attrfiltr['old'])){
					$attr = $_attrfiltr['old'];
				}else{
					$attr = $_attrfiltr['old'];
					$attr[] = $_attrfiltr['attr'];
				}
			}else {
				$attr[] = $_attrfiltr['attr'];
			}
		}
		return $attr;
	}
	
	
	/**
	 * 返回筛选显示信息
	 * @param array $_condition
	 * @return array $info
	 */
	function conditioninfo($_condition){
		$info = array();
// 		if($_condition['cate']){
// 			$cates = $this->catetochildren($_condition['cate']);
// 			$info['cate'] = $this->arr2to1($cates,'id');
// 			dump($cates);
// 		}
		if($_condition['brand']){
			$info['brand'] = $this->brandinfo($_condition['brand']);
		}
		if($_condition['attr']){
			$info['attr'] = $this->attr($_condition['attr']);
		}
		$info['keyword'] = $_condition['keyword'];
		return $info;
	}
	
	
	/**
	 * 返回品牌下的产品
	 * @param string | array $_bid
	 * @return array $ids
	 */
	function brandtopro($_bid){
		$model = M('Product');
		$bid = is_array($_bid) ? $_bid : array($_bid);
		$where = array();
		$where['brand_id'] = array('IN',implode(',', $bid));
		$where['status'] = 1;
		$ids = $model->field('id')->where($where)->select();
// 		echo $model->getLastSql();
		$ids = $this->arr2to1($ids,'id');
		return $ids;
	}
	
	/**
	 * 返回分类下的产品
	 * @param string | array $_cate
	 * @return array $ids;
	 */
	function catetopro($_cate){
		$model = M();
		$cate = is_array($_cate) ? $_cate : array($_cate);
		$sql = "SELECT p.id FROM product p LEFT JOIN product_to_category_tag c ON p.id=c.product_id WHERE p.`status`=1 AND c.category_tag_id IN (".implode(',', $cate).") order by sequence desc,id desc";
		$ids = $model->query($sql);	
		$ids = $this->arr2to1($ids,'id');
		return $ids;
	}
	
	/**
	 * 返回子级分类
	 * @param array $_cate
	 * @param array $_pid
	 * @param array $_level
	 * @return array $this->tree
	 */
	function catetochildren ($_pid = 0,$_cate = array(),$_level = 1) {
		if($_cate){
			foreach ($_cate as $k => $v){
				if($v['parent_id'] == $_pid){
					$v['level'] = $_level;
					$this->catechildren[$v['id']] = $v;
					$this->catetochildren( $v['id'],$_cate,$_level+1);
				}
			}
		}else{
			$temp = $this->_cateslist();
			$_cate = field2key($temp, 'id');
			$this->catechildren[$_pid] = $_cate[$_pid];
			$this->catechildren[$_pid]['level'] = $_level;
			$this->catetochildren($_pid,$_cate);
		}
		return $this->catechildren;
	}
	
	/**
	 * 返回分类列表
	 * @return array $cate
	 */
	function _cateslist() {
		$model = M('ProductCategoryTag');
		$cate = $model->field('id,name,parent_id')->where(array('type'=>1,'status'=>1))->select();
		return $cate;
	}
	
	/**
	 * 返回属性下的产品
	 * @param array $_attrs 属性
	 * @param string $_group 是否要分组筛选
	 * @return array $ids;
	 */
	function attrstopro($_attrs,$_group = TRUE,$catid = 3){
		$model = M();
		$attr = array();
		if($_group){
			$proids = array();
			$temp = $this->attrfiltrs($_attrs,$catid);
			foreach ($temp as $k => $v){
				$attrs = 'a.attribute_id IN ('.implode(',', $v).')';
				$sql = "SELECT p.id FROM product_attribute a LEFT JOIN product p ON a.product_id=p.id WHERE p.`status`=1 AND ".$attrs;
				$ids = $model->query($sql);
// 				echo $model ->getLastSql();
				$ids = $this->arr2to1($ids,'id');
				$proids[] = $ids;
			}print_r($proids);
			$attr = $this->intersection($proids);
		}else{
			$attrs = 'a.attribute_id IN ('.implode(',', $_attrs).')';
			$sql = "SELECT * FROM product_attribute a LEFT JOIN product p ON a.product_id=p.id WHERE p.`status`=1 AND ".$attrs;
			$ids = $model->query($sql);
			$attr = $this->arr2to1($ids,'id');
		}
		return $attr;
	}
	
	/**
	 *	keyword search
	 * @param string $_keyword
	 * @return array $proids
	 */
	function keyword($_keyword){
		$model = M();
		$sql = "SELECT p.id FROM product_description d LEFT JOIN product p ON d.product_id=p.id WHERE p.`status`=1 AND d.`name` LIKE '%".$_keyword."%'";
		$proids = $model->query($sql);
		$proids = $this->arr2to1($proids,'id');
		return $proids;
	}
	//筛选 end
}

